package com.zhang.hadoop.netty.nio.channel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: zhang yufei
 * @create: 2022-01-09 16:25
 * @description: 读取数据
 **/
public class NIOFileChannel02 {

    public static void main(String[] args) {
        try {
            //创建文件输入流
            File file = new File("C:\\zhang\\workspace\\data\\nio\\file01.txt");
            FileInputStream fileInputStream = new FileInputStream(file);
            //通过fileInputStream获取对应的FileChannel实际类型FileChannelImpl
            FileChannel fileChannel = fileInputStream.getChannel();
            //创建缓冲区
            ByteBuffer byteBuffer= ByteBuffer.allocate((int)file.length());
            //将通道数据读入到buffer
            fileChannel.read(byteBuffer);
            System.out.println(new String(byteBuffer.array()));
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
